import { useRefValue } from '@gnlab/utils/env-react'
import { Button } from 'antd'
import { EditModal } from '@/desktop/components'
import { type Word, type WordType } from '@/services/common/definition'
import type { Words } from '@/services/resources/words-library'
import { PreviewWord } from '../preview'
import { WordsLibraryFilter, type FilterChildrenProps } from './filter'

export function ImportFromLibrary({
  types,
  importing,
  onFinish,
}: {
  types: WordType[] // 支持导入的内容类型
  importing: boolean
  onFinish: (words?: Word[]) => void
}) {
  const onFinishRef = useRefValue(onFinish)
  const FilterContent = useCallback(
    ({ wordsList }: FilterChildrenProps) => {
      return <Content types={types} onFinish={onFinishRef.current} wordsList={wordsList} />
    },
    [types],
  )

  return <EditModal
    title="从话术库中导入"
    open={importing}
    onCancel={() => onFinish()}
    width={650}
    css={s.modal}
  >
    {importing ? <WordsLibraryFilter RenderComponent={FilterContent} /> : null}
  </EditModal>
}

function Content({
  types,
  onFinish,
  wordsList,
}: {
  types: WordType[]
  onFinish: (words?: Word[]) => void
  wordsList: Words[]
}) {
  const chooseWords = useCallback(
    (words: Words) => {
      const items = words.items.filter(item => types.includes(item.type))
      onFinish(items.length ? items : undefined)
    },
    [types, onFinish],
  )

  return <div css={s.wrap}>
    {wordsList.map(words => <div key={words.id} css={s.words}>
      <Button type="primary" size="small" css={s.choose} onClick={() => chooseWords(words)}>
        选择
      </Button>
      {words.items.map((word, index) => <PreviewWord key={index} word={word} css={s.word} />)}
    </div>)}
  </div>
}
const s = {
  modal: css`
    .ant-modal-content {
      padding-bottom: 0;
    }
  `,
  wrap: css`
    max-height: 70vh;
    min-height: 150px;
    overflow-y: auto;
    padding: 20px;
  `,
  words: css`
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 20px;
    padding-bottom: 20px;
    position: relative;
  `,
  choose: css`
    position: absolute;
    top: 0;
    right: 0;
  `,
  word: css`
    &:not(:last-child) {
      margin-bottom: 12px;
    }
  `,
}
